/// <reference path="../Bootstrap/js/bootstrap.min.js" />
/// <reference path="../Knockout/knockout.mapping-latest.js" />
/// <reference path="../Knockout/knockout-3.3.0.js" />
/// <reference path="mars.validation.js" />
/// <reference path="jquery-1.11.2.min.js" />
/// <reference path="mars.docmgnt.js" />
/// <reference path="mars.masterlists.js" />
/// <reference path="../BootstrapDialog/bootstrap-dialog.min.js" />
/// <reference path="mars.constants.js" />
/// <reference path="../JQueryValidation/jquery.validate.min.js" />

var MarsUtility = {
    GetCurrentUser: function () {
        var currentUser = null;
        var call = $.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/CurrentUser",
            async: false,
            type: "GET",
            dataType: "json",
            headers: {
                Accept: "application/json;odata=verbose"
            }
        });
        call.done(function (data, textStatus, jqXHR) {
            currentUser = data.d;
        });
        call.fail(function (error, textStatus, errorText) {
            BootstrapDialog.alert("Error: " + errorText);
            console.log(JSON.stringify(error));
        });
        return currentUser;
    },

    GetParameterByName: function (name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexString = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexString);
        var found = regex.exec(window.location.search);
        if (found == null) {
            return "";
        }
        return decodeURIComponent(found[1].replace(/\+/g, " "));
    },

    ApplyDateControls: function () {
        $(".input-group.date").datepicker({ format: "mm/dd/yyyy", autoclose: true, })
    },

    GetCurrentDate: function () {
        var d = new Date();
        var month = d.getMonth() + 1;
        var day = d.getDate();
        var output = d.getFullYear() + '-' +
            (('' + month).length < 2 ? '0' : '') + month + '-' +
            (('' + day).length < 2 ? '0' : '') + day;
        return output;
    },

    GetCurrentDateTime: function () {
        var d = new Date();
        return output = d.toGMTString();
    },

    GetFormattedDate: function (dateString) {
        if (dateString != null && dateString != undefined && dateString != "") {
            var d = new Date(dateString);
            var month = d.getMonth() + 1;
            var day = d.getDate();
            var year = d.getFullYear();
            var output = (('' + month).length < 2 ? '0' : '') + month + '/' +
                (('' + day).length < 2 ? '0' : '') + day + '/' + year;
            return output;
        }
    },

    ReplaceAll: function (find, replace, str) {
        return str.replace(new RegExp(find, 'g'), replace);
    },

    GetValidationId: function (modelId) {
        var currentDate = MarsUtility.GetCurrentDate();
        return "M_" + MarsUtility.ReplaceAll("-", "", currentDate).substring(0, 6) + modelId + "_1";
    },

    GetModelId: function () {
        var ModelId = 1;
        var call = $.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('MARS')/items?$select=ModelId&$orderby=ModelId desc&top=25000",
            async: false,
            type: "GET",
            dataType: "json",
            headers: {
                Accept: "application/json;odata=verbose"
            }
        });
        call.done(function (data, textStatus, jqXHR) {
            var listItems = data.d.results;
            if (listItems.length > 0) {
                ModelId = parseInt(listItems[0].ModelId) + 1;
            }
        });
        call.fail(function (jqXHR, textStatus, errorThrown) {
            BootstrapDialog.alert(errorThrown);
        });
        return "" + ModelId + "";
    },

    GetModelSubmitter: function () {
        var modelSubmitter = null;
        var submitter = MarsUtility.GetCurrentUser();
        if (submitter != null) {
            var userRoleObject = MarsUtility.GetUserRole(submitter.LoginName);
            var userRole = "";
            if (userRoleObject != null && userRoleObject.Role != null) {
                for (var i = 0; i < userRoleObject.Role.results.length; i++) {
                    userRole += "*" + userRoleObject.Role.results[i] + "*";
                }
            }
            if (userRole != null && (userRole.indexOf("*Model Submitter*") >= 0 || userRole.indexOf("*Model Owner*") >= 0)) {
                modelSubmitter = new User(submitter.Title, submitter.LoginName, submitter.Email);
            }
        }
        return modelSubmitter;
    },

    GetModelData: function (validationId) {
        var itemData = null;
        var currentUser = MarsUtility.GetCurrentUser();
        if (validationId != "") {
            itemData = ListUtility.GetSingleListItem(_spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('" + MARS_CONSTANTS.MARS_LIST_NAMES.MARS_MAIN + "')/items?$filter=(ValidationId eq '" + validationId + "')");
        }
        else {
            var ms = MarsUtility.GetModelSubmitter();
            itemData = {
                ModelId: "",
                ValidationId: "",
                ModelSubmitter: ms != null ? ms.Name : "",
                //ModelSubmitterUserName: ms != null ? ms.LoginName : "",
                //ModelSubmitterEmail: ms != null ? ms.Email : "",
                ModelName: "",
                DevelopmentSource: "",
                ModelDescription: "",
                VendorPlatform: "",
                ProductionSystem: "",
                TargetSubmissionDate: "",
                ModelActiveByDate: "",
                PlatformOrSystemId: "",
                ScopeSubmitted: "",
                BusinessUnit: "",
                IVGHead: "",
                ModelOwner: "",
                BusinessUnitExecutive: "",
                StreamLead: "",
                MRO: "",
                Tier1UseCases: "",
                Tier2UseCases: "",
                Tier3UseCases: "",
                Tier4UseCases: "",
                CheckedOutToName: "",
                CheckedOutToUserName: "",
                CheckedOutToEmail: "",
                ModelStatus: MARS_CONSTANTS.MODEL_STATUS.NEW,
                ValidationStatus: MARS_CONSTANTS.VALIDATION_STATUS.NEW,

                RiskAcceptanceCommitteeName: "",
                RiskAcceptanceStartDate: "",
                RiskAcceptanceEndDate: "",
                RiskAcceptanceClosingDate: "",


                // Validation Home

                LeadValidator: "",
                ValidationTracker: "Under IVG Review",
                Phase1Progress: "Not Started",
                Phase2Progress: "Not Started",
                Phase3Progress: "Not Started",
                Phase4Progress: "Not Started",
                Phase5Progress: "Not Started",
                Phase6Progress: "Not Started",

                // Validation Home

                // MRS Data Start
                CurrentUserName: "",
                AsOfDate: "",
                RiskFile: "",
                IntrinsicModelQuality: "",
                RiskMitigationIndex: "",
                RMIWithDataPenalty: "",
                ModelQualityScore: "",
                Exposure: "",
                ModelRiskScore: "",
                ExposureComments: "",

                IMQ_A_QUESTIONAIRE: GetQuestionString(MRS_QUESTIONAIRE.IMQ_A_QUESTIONAIRE),
                IMQ_B_QUESTIONAIRE: GetQuestionString(MRS_QUESTIONAIRE.IMQ_B_QUESTIONAIRE),
                IMQ_C_QUESTIONAIRE: GetQuestionString(MRS_QUESTIONAIRE.IMQ_C_QUESTIONAIRE),
                IMQ_D_QUESTIONAIRE: GetQuestionString(MRS_QUESTIONAIRE.IMQ_D_QUESTIONAIRE),
                // MRS Data End

                FindingNumbers: "",
                FindingTypes: "",
                FindingDescriptions: "",
                ActionPlans: "",
                TargetDates: "",
                CompletionDates: "",

                // Ack Document
                ValidatedFor: "",
                ValidationScope: "",
                ValidationStatement: "",
                IVGApprovalExpiryDate: "",
                AcknowledgementDate: "",

                // Chat History
                ChatMessage: "",
                ChatUserUserName: currentUser != null ? currentUser.LoginName : "",
                ChatUserFullName: currentUser != null ? currentUser.Title : "",
                ChatDateTime: "",
            };
        }
        itemData.CurrentUser = currentUser;
        return itemData;
    },

    GetMarsDocuments: function (validationId, folderName) {
        var array = [];
        if (validationId != "") {
            array = DocUtility.GetFilesUnderFolder(MARS_CONSTANTS.MARS_LIST_NAMES.MARS_DOCUMENTS + "/" +
                validationId + "/" + folderName)
        }
        return array;
    },

    SubmitModelInfo: function (metadata) {
        var success = false;
        var modelId = MarsUtility.GetModelId();
        metadata.ModelStatus = MARS_CONSTANTS.MODEL_STATUS.NOT_SUBMITTED;
        metadata.ValidationStatus = MARS_CONSTANTS.VALIDATION_STATUS.NOT_SUBMITTED;
        metadata.ModelId = modelId;
        metadata.Title = metadata.ValidationId = MarsUtility.GetValidationId(modelId);
        success = ListUtility.AddListItem(MARS_CONSTANTS.MARS_LIST_NAMES.MARS_MAIN, metadata);
        if (success) {
            DocUtility.CreateMarsFolders(metadata.ValidationId);
        }
        return success;
    },

    GetNewValidationStatus: function () {
        var newValidationStatus = null;
        if (modelData != null && modelData != undefined) {
            newValidationStatus = modelData.ModelSummaryModel.ValidationStatus();
            switch (modelData.ModelSummaryModel.ValidationStatus()) {
                case MARS_CONSTANTS.VALIDATION_STATUS.NOT_SUBMITTED:
                    if (modelData.ValidationHomeModel.DevelopmentDocuments().length > 0
                       && modelData.ValidationHomeModel.ImplementationDocuments().length > 0
                            && modelData.ValidationHomeModel.IndependentValidationDocuments().length > 0) {
                        newValidationStatus = MARS_CONSTANTS.VALIDATION_STATUS.MODEL_SUBMITTED;
                    }
                    break;
            }
        }
        return newValidationStatus;
    },

    SubmitModelChanges: function (metadata) {
        var success = false;
        metadata.ValidationStatus = MarsUtility.GetNewValidationStatus();
        var requestUri = _spPageContextInfo.webAbsoluteUrl +
            "/_api/Web/Lists/GetByTitle('" + MARS_CONSTANTS.MARS_LIST_NAMES.MARS_MAIN + "')/items?$filter=(ValidationId eq '" + metadata.ValidationId + "')";
        success = ListUtility.UpdateListItem(MARS_CONSTANTS.MARS_LIST_NAMES.MARS_MAIN, requestUri, metadata);
        return success;
    },

    GetUserRole: function (userName) {
        var userName = userName.substring(userName.indexOf("|") + 1);
        var userRole = null;
        var call = $.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('MARS_USER_ROLES')/Items?$select=UserName,FullName,EmailAddress,Role&$filter=(UserName eq '" + userName + "')",
            async: false,
            type: "GET",
            dataType: "json",
            headers: {
                Accept: "application/json;odata=verbose"
            }
        });
        call.done(function (data, textStatus, jqXHR) {
            console.log(_spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('MARS_USER_ROLES')/Items?select=UserName,FullName,EmailAddress,Role&$filter=(UserName eq '" + userName + "')");
            var configValues = data.d.results;
            if (configValues.length > 0) {
                userRole = configValues[0];
            }
        });
        call.fail(function (jqXHR, textStatus, errorThrown) {
            BootstrapDialog.alert("Error: " + errorThrown);
        });
        return userRole;
    },
}

function GetQuestionString(questionArray) {
    var str = "";
    _.each(questionArray, function (question) {
        str += question.QuestionLabel + MARS_CONSTANTS.STRING_SEPERATOR
            + question.RiskAttribute + MARS_CONSTANTS.STRING_SEPERATOR
            + question.Description + MARS_CONSTANTS.STRING_SEPERATOR
            + question.SelectionValue + MARS_CONSTANTS.STRING_SEPERATOR
            + MARS_CONSTANTS.RECORD_SEPERATOR;
    });
    return str;
}